﻿<?php
require_once("dbc.class.php");
class RegisterNewsletterClass extends dbc {
	
	private $name;
	private $error;
	
	public function __construct() {
		parent::__construct();
		
		$this->name = $this->cleaner(@$_POST['email']);
		$this->error = array();
	}
	
	public function process() {
		if($this->validData()) {
			$this->insertEmail();
		}
		return count($this->error)? false : true;
	}
	
	public function insertEmail() {
		if(@$_POST['mode'] == "newsletter") {
			$sql = "INSERT INTO newsletter SET name='{$this->name}', active='1', vip='0'";
			$data = $this->query($var);
			if($data){}
			else {
				$this->error[] = "Coult not inject values to database";
			}
		}
	}
	
	public function validData() {
		if($this->ifExists()){ 
			$this->error[] = "Email adressen finns redan i databasen";
		}
		if(empty($this->name)){ 
			$this->error[] = "Du måste fylla i en e-post";
		}
		return count($this->error)? false : true;
	}
	
	public function ifExists() {
		$sql = "SELECT * FROM newsletter WHERE name='{$this->name}'";
		$data = $this->query($sql);
		return (mysqli_num_rows($data))? true : false;
	}
	
	public function errors() {
		echo "<h3>Errors</h3>";
		foreach($this->error as $key=>$val) {
			echo $val."<br />";
		}
	}
	
	public function cleaner($var) {
		$dbc = $this->dbConnect();
		return mysqli_real_escape_string($dbc, trim($var));
	}
	
}
?>